//
//  ExersesAnswerResultViewController.m
//  ShowYork
//
//  Created by hxh on 2020/9/10.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "ExercisesAnswerResultViewController.h"
#import "ExercisesPageViewController.h"
#import "ExercisesContainViewController.h"
#import "ExercisesAnswerResultItemCell.h"
#import "ExercisesAnswerResultScoreCell.h"
#import "ExercisesAnswerResultHeaderView.h"
#import "ExercisesAnswerResultFooterView.h"
#import "ExercisesAnswerFeedbackView.h"
#import "ExercisesFeedbackTypeView.h"
#import "LessonDetailViewController.h"
@interface ExercisesAnswerResultViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,ExercisesAnswerResultItemCellDelegate>
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)UIImageView *coverImgView;
@property (nonatomic,strong)UIView *bottomView;
@property (nonatomic,strong)UIView *bottomLine;
@property (nonatomic,strong)UIButton *allBtn;
@property (nonatomic,strong)UIButton *otherBtn;
@property (nonatomic,strong)UIView *line;

@property (nonatomic,strong)ExercisesAnswerFeedbackView *feedbackView;

@property (nonatomic,strong)UIView *titleView;

@end

@implementation ExercisesAnswerResultViewController

- (UIStatusBarStyle)preferredStatusBarStyle {
    
    return UIStatusBarStyleLightContent;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
        

    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.isHideNavBar = YES;
    

    
    self.coverImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"exercises_tag_cover"]];
    self.coverImgView.contentMode = UIViewContentModeScaleAspectFill;
    self.coverImgView.layer.masksToBounds = YES;
    [self.view addSubview:self.coverImgView];
    
    self.coverImgView.cl_width = kScreenW;
    
    
    self.titleView = [[UIView alloc]init];
    [self.view addSubview:self.titleView];
    [self.titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(44);
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT);
    }];
    
    UIButton *feedbackBtn = [[UIButton alloc]init];
    [feedbackBtn addTarget:self action:@selector(feedbackMethod) forControlEvents:UIControlEventTouchUpInside];
    [feedbackBtn setImage:[UIImage imageNamed:@"exercises_tag_feed"] forState:UIControlStateNormal];
    
    [self.titleView addSubview:feedbackBtn];
    [feedbackBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.titleView).offset(-16);
        make.centerY.equalTo(self.titleView);
    }];
    UIButton *backBtn = [[UIButton alloc]init];
    [backBtn setImage:[UIImage imageNamed:@"common_back_normal_tag"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.titleView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.titleView).offset(16);
        make.centerY.equalTo(self.titleView);
    }];
    
    UILabel *lb = [[UILabel alloc]init];
    lb.text = @"练习报告";
    lb.textColor = [UIColor whiteColor];
    lb.font = [UIFont boldSystemFontOfSize:18];
    [self.titleView addSubview:lb];
    [lb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.titleView);
    }];
    
    self.bottomView = [[UIView alloc]initWithFrame:CGRectZero];
    self.bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bottomView];

    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
         if (@available(iOS 11,*)) {
             make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
             make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
         }else{
             make.left.equalTo(self.view);
             make.right.equalTo(self.view);

         }
        make.bottom.equalTo(self.view);
        make.height.mas_equalTo(44.0f + GK_SAVEAREA_BTM);
    }];


    self.allBtn = [[UIButton alloc]initWithFrame:CGRectZero];
    [self.allBtn setTitle:@"查看解析" forState:UIControlStateNormal];
    [self.allBtn setImage:[UIImage imageNamed:@"exerciese_tag_all"] forState:UIControlStateNormal];
    [self.allBtn setTitleColor:RGBA(51, 51, 51, 1) forState:UIControlStateNormal];
    self.allBtn.titleLabel.font = font(14);
    self.allBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 15);
    [self.allBtn addTarget:self action:@selector(allMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.allBtn];

    self.otherBtn = [[UIButton alloc]initWithFrame:CGRectZero];
    [self.otherBtn setTitle:@"错题解析" forState:UIControlStateNormal];
    [self.otherBtn setImage:[UIImage imageNamed:@"exerciese_tag_error"] forState:UIControlStateNormal];
    [self.otherBtn setImage:[UIImage imageNamed:@"exerciese_error_unSelecte"] forState:UIControlStateDisabled];
    [self.otherBtn setTitleColor:RGBA(51, 51, 51, 1) forState:UIControlStateNormal];
    [self.otherBtn setTitleColor:RGBA(204, 204, 204, 1) forState:UIControlStateDisabled];
    self.otherBtn.titleLabel.font = font(14);
    self.otherBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 15);
    [self.otherBtn addTarget:self action:@selector(otherMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.otherBtn];

    [self.allBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(self.bottomView);
        make.size.mas_equalTo(CGSizeMake(kScreenW * 0.5, 44));
    }];
    [self.otherBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.mas_equalTo(self.bottomView);
        make.size.mas_equalTo(CGSizeMake(kScreenW * 0.5, 44));
    }];

    self.line = [[UIView alloc]init];
    self.line.backgroundColor = RGBA(226, 226, 226, 1);
    [self.bottomView addSubview:self.line];

    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.allBtn);
        make.width.mas_equalTo(1);
        make.height.mas_equalTo(14);
        make.centerX.equalTo(self.bottomView);
    }];

    self.bottomLine = [[UIView alloc]init];
    self.bottomLine.backgroundColor = RGBA(226, 226, 226, 1);
    [self.bottomView addSubview:self.bottomLine];
    [self.bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.bottomView);
        make.height.mas_equalTo(0.5);
    }];


    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.bounces = NO;

    [self.view addSubview:self.collectionView];

    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.view).offset(-16);
        make.top.equalTo(self.titleView.mas_bottom);
        make.bottom.mas_equalTo(self.bottomView.mas_top);
    }];


    [self.collectionView registerClass:[ExercisesAnswerResultScoreCell class] forCellWithReuseIdentifier:@"ExercisesAnswerResultScoreCell"];
    [self.collectionView registerClass:[ExercisesAnswerResultItemCell class] forCellWithReuseIdentifier:@"ExercisesAnswerResultItemCell"];
    [self.collectionView registerClass:[ExercisesAnswerResultHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ExercisesAnswerResultHeaderView"];
    [self.collectionView registerClass:[ExercisesAnswerResultFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"ExercisesAnswerResultFooterView"];

    self.collectionView.backgroundColor = [UIColor clearColor];
    self.view.backgroundColor = RGBA(248, 248, 248, 1);

    // Do any additional setup after loading the view.

    if (self.dtlModel == nil) {
        [self showDataLoadState];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"lessonId"] = self.lessonId;
        param[@"userId"] = [RPAppManager getCustomerId];
        param[@"md5"] = [RPAppManager md5StrWithApi:GetUserAnswer];
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetUserAnswer) parames:param success:^(id responseObj) {

            self.dtlModel = [ExercisesPaperResultModel mj_objectWithKeyValues:responseObj[RESPONSE]];
            // 解析数据
            [self.dtlModel.paper modifyObject];

            self.collectionView.backgroundColor = [UIColor whiteColor];

            [self hideDataLoadLoadState];

            // 判断有没有错误
            self.otherBtn.enabled = self.dtlModel.paper.existError;

            self.otherBtn.userInteractionEnabled = self.dtlModel.paper.existError;


            [self.collectionView reloadData];

        } failure:^(id error) {

            [self hideDataLoadLoadState];
        }];
    }else{

        [self.dtlModel.paper modifyObject];

        // 判断有没有错误
        self.otherBtn.enabled = self.dtlModel.paper.existError;

        self.otherBtn.userInteractionEnabled = self.dtlModel.paper.existError;

        self.collectionView.backgroundColor = [UIColor whiteColor];
    }
//
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (self.dtlModel == nil) {
        return 0;
    }
    return self.dtlModel.paper.titleItems.count + 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        ExercisesTitleModel *titleModel = self.dtlModel.paper.titleItems[section - 1];
        return titleModel.questionItems.count;
    }
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        ExercisesAnswerResultScoreCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ExercisesAnswerResultScoreCell" forIndexPath:indexPath];
        [cell setModel:self.dtlModel];
        return cell;
    }
    
    ExercisesAnswerResultItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ExercisesAnswerResultItemCell" forIndexPath:indexPath];
    ExercisesQuqestionModel * model = self.dtlModel.resultArray[indexPath.section - 1][indexPath.item];
    [cell setResultItem:model atIndex:indexPath.row];
    cell.delegate = self;
    return cell;

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return CGSizeMake(kScreenW - 32, self.dtlModel.celHeight);
    }
     return CGSizeMake(38, 38);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            if (indexPath.section != 0) {
                ExercisesAnswerResultHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ExercisesAnswerResultHeaderView" forIndexPath:indexPath];
                [headerView setResultModel:self.dtlModel atIndex:indexPath.section - 1];
                return headerView;
            }

        }
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        if (indexPath.section != 0) {
            ExercisesAnswerResultFooterView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"ExercisesAnswerResultFooterView" forIndexPath:indexPath];
            return footerView;
        }
    }
    return nil;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (section != 0) {
       return UIEdgeInsetsMake(24,28,24,28);
    }
    return UIEdgeInsetsZero;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (section != 0) {
        return 24.0f;
    }
    return 0.0f;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (section != 0) {
        return 24.0f;
    }
    return 0.0f;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section != 0) {
        return CGSizeMake(kScreenW - 32, 44);
    }
    return CGSizeZero;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (section != 0 && section < self.dtlModel.paper.titleItems.count) {
        return CGSizeMake(kScreenH - 32, 1);
    }
    return CGSizeZero;
}

#pragma mark - ExercisesAnswerResultItemCellDelegate
- (void)didSelecteAtIResultItem:(ExercisesQuqestionModel *)currentModel{
    
    self.dtlModel.paper.onlyQuestion = YES;
    self.dtlModel.paper.onlyError = NO;
    self.dtlModel.paper.errorQuestion = NO;
    
    // 初始化
    ExercisesContainViewController *vc = [[ExercisesContainViewController alloc]initWithDetailModel:self.dtlModel.paper selectedQuestionItem:currentModel enterType:XHLESSONCONTAINENTERTRAGET];
    [self.navigationController pushViewController:vc animated:YES];
    
}


#pragma mark - other

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

- (void)feedbackMethod{
    
    __weak typeof(self)weakSelf = self;
    ExercisesFeedbackTypeView *typeView = [[ExercisesFeedbackTypeView alloc]initWithCompleteBlock:^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.feedbackView = [[ExercisesAnswerFeedbackView alloc]initWithCompleteBlock:^(NSString * _Nonnull content) {
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            param[@"content"] = content;
            param[@"md5"] = [RPAppManager md5StrWithApi:AddFeedback];
            param[@"userId"] = [RPAppManager getCustomerId];
            [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(AddFeedback) parames:param success:^(id responseObj) {
                [strongSelf.feedbackView hide];
                [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"感谢您的反馈，我们会努力进步的" duration:2 finishHandler:nil];
            } failure:^(id error) {

            }];
        }];
        [strongSelf.feedbackView show];
    }];
    [typeView show];
}

- (void)backMethod{

    
    
    if (self.isFinishVideo) {
        UIViewController *parentVC = self.presentingViewController;
        UIViewController *bottomVC;
        while (parentVC) {
            bottomVC = parentVC;
            parentVC = parentVC.presentingViewController;
        }
        [bottomVC dismissViewControllerAnimated:NO completion:nil];

    }else{

        __block NSInteger index = -1;
        [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[ExercisesPageViewController class]]) {
                index = idx;
                *stop = YES;
            }
        }];
        
        if (index != -1) {
            [self.navigationController popToViewController:self.navigationController.viewControllers[index - 1] animated:YES];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    
}


- (void)allMethod{
    
    [MobClick event:@"exercise_all_result_click"];
    if (self.dtlModel == nil) {
        return;
    }
    self.dtlModel.paper.onlyError = NO;
    self.dtlModel.paper.errorQuestion = NO;
    self.dtlModel.paper.onlyQuestion = YES;
    ExercisesContainViewController *vc = [[ExercisesContainViewController alloc]initWithDetailModel:self.dtlModel.paper selectedQuestionItem:nil enterType:XHLESSONCONTAINENTERRESULTALL];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)otherMethod{
    [MobClick event:@"exercise_error_result_click"];
    if (self.dtlModel == nil) {
        return;
    }
    self.dtlModel.paper.onlyQuestion = NO;
    self.dtlModel.paper.errorQuestion = NO;
    self.dtlModel.paper.onlyError = YES;
    ExercisesContainViewController *vc = [[ExercisesContainViewController alloc]initWithDetailModel:self.dtlModel.paper selectedQuestionItem:nil enterType:XHLESSONCONTAINENTERRESULTERROR];
    [self.navigationController pushViewController:vc animated:YES];
}

@end
